package com.fourth.utils;

import com.alibaba.druid.pool.DruidDataSource;
import com.alibaba.druid.pool.DruidPooledConnection;
import com.alibaba.fastjson.JSONObject;
import com.fourth.common.GmallConfig;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;

import java.sql.Connection;
import java.util.List;

/**
 * @Author CZQ
 * @Date 2022/7/31 13:51
 * @Version 1.0
 */
public class DimUtil {
    public static JSONObject getDimInfo(Jedis jedis, Connection connection, String tableName, String key) throws Exception {

        //读取Redis中的维表数据
        String redisKey = "DIM:" + tableName + ":" + key;
        String dimInfoStr = jedis.get(redisKey);
        if (dimInfoStr != null) {
            //重置过期时间
            jedis.expire(redisKey, 24 * 60 * 60);
            return JSONObject.parseObject(dimInfoStr);
        }

        //拼接SQL
        String querySql = "select * from " + GmallConfig.HBASE_SCHEMA + "." + tableName + " where id='" + key + "'";

        //查询
        List<JSONObject> queryList = JdbcUtil.queryList(connection, querySql, JSONObject.class, false);
        JSONObject dimInfo = queryList.get(0);
        //将从Phoenix查询到的数据写入到Redis
        jedis.set(redisKey, dimInfo.toJSONString());
        //设置过期时间
        jedis.expire(redisKey, 24 * 60 * 60);

        //返回结果
        return dimInfo;
    }

    //删除操作
    public static void delDimInfo(Jedis jedis,  String tableName, String key){
        //读取Redis中的维表数据
        String redisKey = "DIM:" + tableName + ":" + key;
        jedis.del(redisKey);


    }

/*    public static void main(String[] args) throws Exception {
        DruidDataSource dataSource = DruidDSUtil.createDataSource();
        DruidPooledConnection connection = dataSource.getConnection();

        JedisPool jedisPool = JedisPoolUtil.getJedisPool();
        Jedis jedis = jedisPool.getResource();
*//*
        long start = System.currentTimeMillis();

        System.out.println(getDimInfo(jedis,connection, "DIM_BASE_TRADEMARK", "19"));
        long end = System.currentTimeMillis();

        System.out.println(getDimInfo(jedis,connection, "DIM_BASE_TRADEMARK", "19"));
        long end2 = System.currentTimeMillis();

        System.out.println(end - start);
        System.out.println(end2 - end);*//*

        jedis.close();
        jedisPool.close();
        connection.close();
        dataSource.close();
    }*/
}
